// 获取页面元素
const usernameInput = document.getElementById('username');
const loginButton = document.getElementById('login-button');
const logoutButton = document.getElementById('logout-button');
const statusElement = document.getElementById('status');
const privateReceiverInput = document.getElementById('private-receiver');
const privateMessageInput = document.getElementById('private-message');
const privateSendButton = document.getElementById('private-send-button');
const groupMessageInput = document.getElementById('group-message');
const groupSendButton = document.getElementById('group-send-button');
const privateMessageList = document.getElementById('private-message-list');
const groupMessageList = document.getElementById('group-message-list');
const groupNameInput = document.getElementById('group-name');
const joinGroupButton = document.getElementById('join-group-button');
// 获取保存消息的按钮
const saveMessagesButton = document.getElementById('save-messages-button');

// 用于存储已接收消息的 ID 或唯一标识，这里简单用消息内容和发送者作为标识
const receivedMessages = new Set();
let joinedGroup = false;

// 登录按钮点击事件
loginButton.addEventListener('click', async () => {
    const username = usernameInput.value;
    if (username) {
        try {
            const response = await fetch(`/users/${username}/login`, {
                method: 'POST'
            });
            if (response.ok) {
                statusElement.textContent = `已登录，用户名：${username}`;
                loginButton.disabled = true;
                logoutButton.disabled = false;
                document.getElementById('login-section').style.display = 'none';
                document.getElementById('message-section').style.display = 'block';
                startListeningMessages(username);
                startListeningGroupMessages(username); // 新增监听群聊消息
            }
        } catch (error) {
            console.error('登录失败:', error);
            statusElement.textContent = '登录失败，请重试';
        }
    }
});

// 登出按钮点击事件
logoutButton.addEventListener('click', async () => {
    const username = usernameInput.value;
    if (username) {
        try {
            const response = await fetch(`/users/${username}/logout`, {
                method: 'POST'
            });
            if (response.ok) {
                statusElement.textContent = '已登出';
                loginButton.disabled = false;
                logoutButton.disabled = true;
                document.getElementById('login-section').style.display = 'block';
                document.getElementById('message-section').style.display = 'none';
                // 登出时清空已接收消息记录
                receivedMessages.clear();
                joinedGroup = false;
                groupSendButton.disabled = true;
            }
        } catch (error) {
            console.error('登出失败:', error);
            statusElement.textContent = '登出失败，请重试';
        }
    }
});

// 发送私聊按钮点击事件
privateSendButton.addEventListener('click', async () => {
    const sender = usernameInput.value;
    const receiver = privateReceiverInput.value;
    const message = privateMessageInput.value;
    if (sender && receiver && message) {
        const messageObj = {
            sender: sender,
            receiver: receiver,
            content: message
        };
        try {
            const response = await fetch('/messages/private', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(messageObj)
            });
            if (response.ok) {
                const newMessage = document.createElement('p');
                newMessage.textContent = `${sender} -> ${receiver}: ${message}`;
                newMessage.textContent = `${sender} -> ${receiver}: ${message}`;
                privateMessageList.appendChild(newMessage);
                privateMessageInput.value = '';
                // 标记自己发送的私聊消息为已接收
                const messageKey = `${messageObj.sender}-${messageObj.receiver}-${messageObj.content}`;
                receivedMessages.add(messageKey);
            }
        } catch (error) {
            console.error('发送私聊失败:', error);
        }
    }
});

// 加入群聊按钮点击事件
joinGroupButton.addEventListener('click', async () => {
    const username = usernameInput.value;
    const groupName = groupNameInput.value;
    if (username && groupName) {
        try {
            const response = await fetch(`/groups/${groupName}/join?username=${username}`, {
                method: 'POST'
            });
            if (response.ok) {
                const isJoined = await response.json();
                if (isJoined) {
                    joinedGroup = true;
                    groupSendButton.disabled = false;
                    alert('成功加入群聊');
                } else {
                    alert('加入群聊失败');
                }
            }
        } catch (error) {
            console.error('加入群聊请求失败:', error);
        }
    }
});

// 发送群聊按钮点击事件
groupSendButton.addEventListener('click', async () => {
    if (!joinedGroup) {
        alert('请先加入群聊');
        return;
    }
    const sender = usernameInput.value;
    const message = groupMessageInput.value;
    const groupName = groupNameInput.value;
    if (sender && message && groupName) {
        const messageObj = {
            sender: sender,
            receiver: '',
            content: message
        };
        try {
            const response = await fetch(`/groups/${groupName}/send?username=${sender}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(messageObj)
            });
            if (response.ok) {
                const isSent = await response.json();
                if (isSent) {
                    const newMessage = document.createElement('p');
                    newMessage.textContent = `${sender}: ${message}`;
                    groupMessageList.appendChild(newMessage);
                    groupMessageInput.value = '';
                    // 标记自己发送的群聊消息为已接收
                    const messageKey = `${messageObj.sender}-${messageObj.receiver}-${messageObj.content}`;
                    receivedMessages.add(messageKey);
                } else {
                    alert('发送群聊消息失败');
                }
            }
        } catch (error) {
            console.error('发送群聊消息请求失败:', error);
        }
    }
});

// 抽离翻译逻辑到一个独立的函数
async function translateText(text) {
    try {
        const translateResponse = await fetch('/translate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ text: text })
        });
        if (translateResponse.ok) {
            const translateData = await translateResponse.json();
            return translateData.trans_result[0].dst;
        }
    } catch (translateError) {
        console.error('翻译失败:', translateError);
    }
    return text;
}

// 监听私聊消息
async function startListeningMessages(username) {
    setInterval(async () => {
        try {
            const response = await fetch(`/messages/${username}`);
            if (response.ok) {
                const messages = await response.json();
                console.log('Received private messages:', messages);
                messages.forEach(async (message) => {
                    const messageKey = `${message.sender}-${message.receiver}-${message.content}`;
                    if (!receivedMessages.has(messageKey)) {
                        let displayContent = message.content;
                        // 判断消息是否为英文
                        if (/^[a-zA-Z\s.,!?]+$/.test(message.content)) {
                            const translatedContent = await translateText(message.content);
                            displayContent = `${message.content}(${translatedContent})`;
                        }
                        if (message.receiver === '') {
                            // 群聊消息
                            const newMessage = document.createElement('p');
                            newMessage.textContent = `${message.sender}: ${displayContent}`;
                            groupMessageList.appendChild(newMessage);
                        } else {
                            // 私聊消息
                            const newMessage = document.createElement('p');
                            newMessage.textContent = `${message.sender} -> ${message.receiver}: ${displayContent}`;
                            privateMessageList.appendChild(newMessage);
                        }
                        // 标记该消息为已接收
                        receivedMessages.add(messageKey);
                    }
                });
            }
        } catch (error) {
            console.error('获取私聊消息失败:', error);
        }
    }, 3000); // 每 3 秒检查一次新消息
}

// 监听群聊消息
async function startListeningGroupMessages(username) {
    setInterval(async () => {
        const groupName = groupNameInput.value;
        if (groupName) {
            try {
                const response = await fetch(`/messages/group/${groupName}`);
                if (response.ok) {
                    const messages = await response.json();
                    console.log('Received group messages:', messages);
                    messages.forEach(async (message) => {
                        const messageKey = `${message.sender}-${message.receiver}-${message.content}`;
                        if (!receivedMessages.has(messageKey)) {
                            let displayContent = message.content;
                            // 判断消息是否为英文
                            if (/^[a-zA-Z\s.,!?]+$/.test(message.content)) {
                                const translatedContent = await translateText(message.content);
                                displayContent = `${message.content}(${translatedContent})`;
                            }
                            const newMessage = document.createElement('p');
                            newMessage.textContent = `${message.sender}: ${displayContent}`;
                            groupMessageList.appendChild(newMessage);
                            // 标记该消息为已接收
                            receivedMessages.add(messageKey);
                        }
                    });
                }
            } catch (error) {
                console.error('获取群聊消息失败:', error);
            }
        }
    }, 3000); // 每 3 秒检查一次新消息
}
// 保存消息按钮点击事件
saveMessagesButton.addEventListener('click', () => {
    let messagesText = '';

    // 获取私聊消息
    const privateMessages = privateMessageList.querySelectorAll('p');
    privateMessages.forEach(message => {
        messagesText += message.textContent + '\n';
    });

    // 获取群聊消息
    const groupMessages = groupMessageList.querySelectorAll('p');
    groupMessages.forEach(message => {
        messagesText += message.textContent + '\n';
    });

    // 创建一个Blob对象
    const blob = new Blob([messagesText], {type: 'text/plain;charset=utf-8'});

    // 创建一个下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'chat_messages.txt';

    // 模拟点击下载链接
    link.click();

    // 释放URL对象
    URL.revokeObjectURL(link.href);
});